# -*- coding:utf-8 -*-

import os
import math
import time
import thread
import threading
import fnmatch
import shutil
import random

class StatLog(threading.Thread):
    def __init__(self, out_dir="../log", flag=True):
        threading.Thread.__init__(self)
        self.mutex_lock = thread.allocate_lock()
        self.out_dir = out_dir
        self.fun_flag = flag
        self.thread_id = 0
        self.log_msg = ""
    
    def write_msg_to_stat_log(self):
        """
        写统计日志到文件
        """
        while True:
            self.mutex_lock.acquire()
            try:
                if self.log_msg:
                    try:
                        file_time = time.strftime("%Y%m%d%H%M", time.localtime())
                        log_path = os.path.join(self.out_dir, "FormerStat_%s_%s.log"%(file_time, self.thread_id))
                        fp = open(log_path, "a")
                        fp.write(self.log_msg)
                        fp.close()
                        self.log_msg = ""
                    except Exception, msg:
                        print msg
                    except:
                        pass
            finally:
                self.mutex_lock.release()
            time.sleep(2)
        
    def move_stat_log_to_bak_dir(self):
        """
        移动统计日志到备份目录
        """
        while True:
            try:
                local_time = time.strftime("%Y%m%d%H", time.localtime())
                log_list = os.listdir(self.out_dir)
                log_list = fnmatch.filter(log_list, "FormerStat_*_*.log")
                for log_file in log_list:
                    src_path = os.path.join(self.out_dir, log_file)
                    modify_time = os.path.getmtime(src_path)
                    file_time = log_file.split("_")[1]
                    if local_time != file_time and time.time() - modify_time > 5:
                        dst_dir_path = os.path.join(self.out_dir, "stat", file_time[:8], file_time[8:])
                        if not os.path.exists(dst_dir_path):
                            os.makedirs(dst_dir_path)
                        dst_path = os.path.join(dst_dir_path, log_file)
                        shutil.move(src_path, dst_path) 
            except Exception, msg:
                print msg
            except:
                pass                    
            time.sleep(60) 
            
    def info(self, msg):
        """
        添加统计日志信息
        """
        if not self.fun_flag:
            raise 
        self.mutex_lock.acquire()
        self.log_msg += msg
        self.mutex_lock.release()        
        
    def write_statlog_amply(self, filename, statinfo, status, author, datadest=""):
        deal_date = int(time.time())
        local_time = time.localtime()
        data_date = time.strftime("%Y%m%d", local_time)
        deal_time = time.strftime("%Y-%m-%d %H:%M:%S", local_time)        
        if 0 == status:
            self.info("%s\tUpareaid:%s\tProtypeDesc:%s\tDataSource:%s\tDataDate:%s\tDealDate:%s\tFileName:%s\tFileSize:%s\tFileType:%s\tStatus:%d\tSuccRecordNum:%s\tStatProgram:DataDispatch.%s\tDataDest:%s\tFileTime:%s\n"% \
                      (deal_time,statinfo.uparea_id,statinfo.protype_desc,statinfo.data_source,statinfo.data_date,deal_date,filename,statinfo.file_size,statinfo.file_type,status,statinfo.record_num, author, datadest, statinfo.file_time))
        else:
            self.info("%s\tUpareaid:%s\tProtypeDesc:%s\tDataSource:%s\tDataDate:%s\tDealDate:%s\tFileName:%s\tFileSize:%s\tFileType:%s\tStatus:%d\tErrRecordNum:%s\tStatProgram:DataDispatch.%s\tDataDest:%s\tFileTime:%s\n"% \
                      (deal_time, statinfo.uparea_id,statinfo.protype_desc,statinfo.data_source,statinfo.data_date,deal_date,filename,statinfo.file_size,statinfo.file_type,status,statinfo.record_num, author, datadest, statinfo.file_time))

    def write_statlog_curtly(self, filename, filesize, filetype, status, author, datadest=""):
        deal_date = int(time.time())
        local_time = time.localtime()
        data_date = time.strftime("%Y%m%d", local_time)
        deal_time = time.strftime("%Y-%m-%d %H:%M:%S", local_time)
        self.info("%s\tDataDate:%s\tDealDate:%d\tDataDest:%s\tFileName:%s\tStatus:%d\tStatProgram:DataDispatch.%s\tFileSize:%s\tFileType:%s\tFileTime:\n"% \
                  (deal_time, data_date, deal_date, datadest, filename, status, author, filesize, filetype))
            
    def run(self):
        if self.fun_flag:
            thread_id = int(math.fabs(thread.get_ident())) + random.randint(0, 1000)
            self.thread_id = str(thread_id)
            #print "---->", self.thread_id, "<----"
            self.write_msg_to_stat_log()
        else:
            self.move_stat_log_to_bak_dir()
    
import unittest
from StatInfo import StatInfo
class StatLogTestCase(unittest.TestCase):
    def setUp(self):
        self.statlog = StatLog("../log", True)
    
    def tearDown(self):
        pass
        
    def testCurtlyWrite(self):
        self.statlog.daemon = True
        self.statlog.start()
    
        filename = "MASS_1234567890_123456_HTTP_320100_111.bcp"
        filesize = "1024"
        filetype = "bcp"
        statue = 0
        author = "test"
        datadest = "no"
        self.statlog.write_statlog_curtly(filename, filesize, filetype, statue, author, datadest)
        
        time.sleep(5)
        
    def testAmplyWrite(self):
        self.statlog.daemon = True
        self.statlog.start()
        
        statinfo = StatInfo()
        statinfo.data_date = "20101010"
        statinfo.data_source = "111"
        statinfo.file_size = "512"
        statinfo.file_type = "bcp"
        statinfo.protype_desc = "EMAIL"
        statinfo.record_num = "1213"
        statinfo.uparea_id = "320200"
        
        status = -1
        author = "test"
        datadest = "yes"
        filename = "MASS_1234567890_123456_HTTP_320100_111.bcp"
        self.statlog.wtite_statlog_amply(filename, statinfo, status, author, datadest)
        
        time.sleep(5)
        
        
if __name__ == "__main__":
    suite = unittest.TestSuite()
    suite.addTest(StatLogTestCase("testAmplyWrite"))
    suite.addTest(StatLogTestCase("testCurtlyWrite"))
    
    runner = unittest.TextTestRunner()
    runner.run(suite)

    